package com.utils;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author Jacinlab
 * @file List2MapUtil.java
 * @CopyRight (C) http://www.jacinlab.xin
 * @brief 将List<Entity> 转换为Map
 * @email 649355204@qq.com
 * @time 2019/9/26 16:25
 */

public class List2MapUtil {
    /**
     * 将对象列表按名称分类成Map（分类名必与对象的某 get方法的后的名一致
     *               <如:getName则传入“Name">
     *                   liang 2019/11/28: 加入首字母大写方法，已不需要手动首字母大写
     * @param list list
     * @param name 属性名
     * @return 提成Map<String, List<>>
     */
    public static <T> Map<String, List<T>> list2Map(List<T> list, String name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Map<String,List<T>> resultMap = new HashMap<>(16);
        name = name.substring(0, 1).toUpperCase() + name.substring(1);
        for (T obj : list) {
            Method method = obj.getClass().getMethod("get" + name);
            String keyName = (String) method.invoke(obj);
            if(StringUtils.isBlank(keyName))
                continue;
            List<T> tempList;
            if (!resultMap.containsKey(keyName)) {
                tempList = new ArrayList<>();
            } else {
                tempList = resultMap.get(keyName);
            }
            tempList.add(obj);
            resultMap.put(keyName, tempList);
        }
        return resultMap;
    }/**
     * 将对象列表按名称分类成Map，value不是列表而是单个实体
     * @param list list
     * @param name 属性名
     * @return 提成Map<String, Object>
     */
    public static <T> Map<String, T> list2MapNotList(List<T> list, String name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Map<String, T> resultMap = new HashMap<>(16);
        name = name.substring(0, 1).toUpperCase() + name.substring(1);

        for (T obj : list) {
            Method method = obj.getClass().getMethod("get" + name);
            String keyName = String.valueOf(method.invoke(obj));
            if(StringUtils.isBlank(keyName)){
                continue;
            }
            resultMap.put(keyName, obj);
        }
        return resultMap;
    }
}
